package com.service.ai;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class QwenChatService {

    private static final Logger logger = LoggerFactory.getLogger(AiChatService.class);

    @Value("${ai.api.url:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation}")
    private String apiUrl;

    @Value("${ai.api.key:}")
    private String apiKey;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper; // 用于打印 JSON

    public String generateReply(String userMessage) {
        if (!StringUtils.hasText(userMessage)) {
            return "请输入您的问题。";
        }

        try {
            // 1. 构建系统提示
            String systemPrompt = "你是一位专业的心理咨询师，请用温暖、简洁、有同理心的中文回答以下问题，不要超过200字。";

            // 2. 构建消息列表
            List<Map<String, String>> messages = new ArrayList<>();

            Map<String, String> systemMsg = new HashMap<>();
            systemMsg.put("role", "system");
            systemMsg.put("content", systemPrompt);
            messages.add(systemMsg);

            Map<String, String> userMsg = new HashMap<>();
            userMsg.put("role", "user");
            userMsg.put("content", userMessage);
            messages.add(userMsg);

            // 3. 构建完整请求体（兼容 Java 8）
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "qwen-max"); // 根据实际模型调整

            // 👇 使用传统方式创建 input map（Java 8 兼容）
            Map<String, Object> inputMap = new HashMap<>();
            inputMap.put("messages", messages);
            requestBody.put("input", inputMap);

            // 4. 打印请求体
            String jsonRequestBody = objectMapper.writeValueAsString(requestBody);
            logger.info("【AI 请求】URL: {}", apiUrl);
            logger.info("【AI 请求体】\n{}", jsonRequestBody);

            // 5. 设置请求头（以阿里云 DashScope 为例）
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            if (StringUtils.hasText(apiKey)) {
                headers.set("X-DashScope-Api-Key", apiKey); // 阿里云专用 Header
            } else {
                logger.warn("AI API Key 未配置！");
            }

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            // 6. 发送请求
            ResponseEntity<Map> response = restTemplate.exchange(
                    apiUrl,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );

            // 7. 打印响应体
            Map<String, Object> responseBody = response.getBody();
            if (responseBody != null) {
                String jsonResponse = objectMapper.writeValueAsString(responseBody);
                logger.info("【AI 响应】状态码: {}", response.getStatusCode());
                logger.info("【AI 响应体】\n{}", jsonResponse);
            }

            // 8. 解析 AI 回复（阿里云格式）
            if (responseBody != null && responseBody.containsKey("output")) {
                Map<String, Object> output = (Map<String, Object>) responseBody.get("output");
                if (output.containsKey("text")) {
                    String reply = (String) output.get("text");
                    return reply != null ? reply.trim() : "AI 未返回有效内容。";
                }
            }

            return "抱歉，AI 暂时无法回答。";

        } catch (Exception e) {
            logger.error("调用 AI 接口异常，用户问题: {}", userMessage, e);
            return "很抱歉，AI 服务暂时不可用，请稍后再试。";
        }
    }
}